<template>
  <div>
    <nav-bar title="实时巡检"></nav-bar>
    <div class="realTimeInspection maxinBox">
      <van-form>
        <van-cell is-link title="问题类别" :value="quistionTypeVal" @click="quistionType = true" />
        <van-field
          v-model="form.pointDesc"
          name="故障点位"
          label="故障点位"
          placeholder="请输入故障点位"
        />
        <van-cell is-link title="危险等级" :value="dangerLevelVal" @click="dangerLevel = true" />
        <van-cell title="负责人" is-link :value="personHead" @click="onChoosePerson('head')" />
        <van-cell title="抄送人" is-link :value="personC" @click="onChoosePerson('cc')" />
        <van-action-sheet v-model="quistionType" :actions="quistionsList" @select="chooseQuistionType" />
        <van-action-sheet v-model="dangerLevel" :actions="level" @select="chooseDangerLevel" />
        <van-cell title="截止日期" @click="showTime" is-link v-if="form.expireDate" :value="form.expireDate | formatDate('YYYY-MM-DD HH:mm')" />
        <van-cell title="截止日期" @click="showTime" is-link v-else :value="form.expireDate" />
        <van-popup v-model="showChooseTime" position="bottom" style="height: 40%">
          <van-datetime-picker
            @confirm="confirm"
            @cancel="showChooseTime = false"
            v-model="currentDate"
            type="datetime"
            title="选择截止时间"
            :min-date="minDate"
            :max-date="maxDate"
          />
        </van-popup>
        <van-field
          class="textarea"
          type="textarea"
          v-model="form.troubleDesc"
          name="问题描述"
          label="问题描述"
          placeholder="请输入问题描述"
          :rules="[{ required: true, message: '请填写问题描述' }]"
        />
        <van-field name="uploader" label="照片上传">
          <template #input>
            <van-uploader multiple :max-count="3" v-model="imagesList" :after-read="onUploader" :before-delete="delUpload" />
          </template>
        </van-field>
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="onSubmit" @click="onSubmit">
            <van-loading type="spinner" v-if="loading" />
            <span v-else>发起实时检</span>
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
  import Bus from '../../../../utils/eventBus.js'
  import moment from 'moment'
  import dashbordAPI from '../../../../api/dashbordAPI.js'
  import realTimeInspectionAPI from '../../../../api/workAPI/realTimeInspectionAPI.js'
  export default {
    data() {
      return {
        islose: false,
        loading: false,
        form: {
          id: this.$route.params.id,
          pointDesc: '',
          category: '',
          expireDate: '',
          handlers: [],
          notifiers: [],
          projectId: localStorage.getItem('projectId'),
          riskLevel: '',
          troubleAttachmentList: [],
          troubleDesc: ''
        },
        personHead: '请选择负责人',
        personC: '请选择抄送人',
        imagesList:[],
        choosePerson: '',
        quistionTypeVal: '',
        dangerLevelVal: '',
        showChooseTime: false,
        minDate: new Date(),
        maxDate: new Date(2025, 10, 1),
        currentDate: new Date(),
        uploader:[],
        questionDesc: '',
        cname: '',
        nickname: '',
        dangerLevel: false,
        quistionType: false,
        level: [{name: 'I级(一般等级)', value: 1}, {name: 'II级(普通危险)', value: 2}, {name: 'III级(非常危险)', value: 3}],
        quistionsList: [],
      }
    },
    methods: {
      onUploader(file) {
        file.status = 'uploading'
        file.message = '上传中'
        dashbordAPI.uploadAvatar(file.file).then(res => {
          this.form.troubleAttachmentList.push(res.fileUrl)
          file.status = ''
          file.message = ''
        }).finally(() => {
          file.status = ''
          file.message = ''
        })
      },
      delUpload(file) {
        this.imagesList.forEach(item => {
          if (item.file.name === file.file.name) {
            let index = this.imagesList.indexOf(item);
            this.imagesList.splice(index, 1)
            this.form.troubleAttachmentList.splice(index, 1)
          }
        })
      },
      // 选择人员
      onChoosePerson(data) {
        this.islose = true
        let realdata
        if (data === 'head') {
          realdata = {
            imagesList: this.imagesList,
            quistionTypeVal: this.quistionTypeVal,
            dangerLevelVal: this.dangerLevelVal
          }
        } else {
          realdata = {
            imagesList: this.imagesList,
            quistionTypeVal: this.quistionTypeVal,
            dangerLevelVal: this.dangerLevelVal
          }
        }
        localStorage.setItem('realTimeForm', JSON.stringify(this.form))
        localStorage.setItem('realTimeData', JSON.stringify(realdata))
        this.$router.push({
          name: 'ChoosePersonal',
          params: {
            data: data
          }
        })
      },
      // 查询问题列表
      getQuistionsList() {
        realTimeInspectionAPI.getQuistionsList().then(res => {
          this.quistionsList = res.map(item => {
            return {
              name: item.text,
              value: item.value
            }
          })
        })
      },
      // 选择问题类别
      chooseQuistionType(item) {
        this.quistionType = false;
        this.form.category = item.value
        this.quistionTypeVal = item.name
      },
      // 选择危险等级
      chooseDangerLevel(item) {
        this.dangerLevel = false;
        this.form.riskLevel = item.value
        this.dangerLevelVal = item.name
      },
      // 选择时间
      showTime() {
        this.showChooseTime = true
      },
      // 日期选择确定按钮
      confirm(val) {
       this.form.expireDate = moment(val).format('YYYY-MM-DD HH:mm')
       this.showChooseTime = false
      },
      // 提交表单
      onSubmit() {
        if (this.form.pointDesc === '') {
          this.$toast.fail('请输入故障点位')
          return
        }
        if (!this.form.category) {
          this.$toast.fail('请选择问题类别')
          return
        }
        if (this.form.expireDate === '') {
          this.$toast.fail('请选择过期时间')
          return
        }
        if (this.form.handlers.length === 0) {
          this.$toast.fail('请选择负责人')
          return
        }
        // if (this.form.notifiers.length === 0) {
        //   this.$toast.fail('请选择抄送人')
        //   return
        // }
        if (!this.form.riskLevel) {
          this.$toast.fail('请选择危险等级')
          return
        }
        if (this.form.troubleDesc === '') {
          this.$toast.fail('请输入问题描述')
          return
        }
        if (this.imagesList.length === 0) {
          this.$toast.fail('请上传图片')
          return
        }
        if (this.form.troubleAttachmentList.length === 0) {
          this.$toast.fail('正在上传服务器... ')
          return
        }
        let form = JSON.parse(JSON.stringify(this.form))
        form.expireDate = moment(this.form.expireDate).format('YYYY-MM-DD HH:mm:ss')
        this.loading = true
        realTimeInspectionAPI.initiate(form).then(res => {
          this.loading = false
          this.$toast('任务发起成功')
          localStorage.removeItem('realTimeForm')
          localStorage.removeItem('realTimeData')
          localStorage.removeItem('personC')
          localStorage.removeItem('personHead')
          localStorage.removeItem('handlers')
          localStorage.removeItem('notifiers')
          this.quistionTypeVal = ''
          this.dangerLevelVal = ''
          this.personHead = ''
          this.personC = ''
          this.form.troubleAttachmentList = []
          this.form.handlers = []
          this.form.notifiers = []
          this.form.pointDesc = ''
          this.form.expireDate = ''
          this.form.troubleDesc = ''
          this.imagesList = []
          this.$router.push({
            name: 'RealTimeInspection'
          })
        }).finally(() => {
          this.loading = false
        })
      },
    },
    destroyed() {
      if(!this.islose){
        localStorage.removeItem('realTimeData')
        localStorage.removeItem('realTimeForm')
        localStorage.removeItem('personC')
        localStorage.removeItem('notifiers')
        localStorage.removeItem('handlers')
        localStorage.removeItem('personHead')
      }
    },
    created() {
      Bus.$on('personHeadList', data => {
        if (data.personType === 'head') {
          this.personHead = data.choosePersonal.map(item => {
            return item.name
          }).join(',')
          this.form.handlers = data.choosePersonal.map(item => {
            return item.userId
          })
          localStorage.setItem('handlers', JSON.stringify(this.form.handlers))
          localStorage.setItem('personHead', this.personHead)
        } else {
          this.personC = data.choosePersonal.map(item => {
            return item.name
          }).join(',')
          this.form.notifiers = data.choosePersonal.map(item => {
            return item.userId
          })
          localStorage.setItem('notifiers', JSON.stringify(this.form.notifiers))
          localStorage.setItem('personC', this.personC)
        }
      })
    },
    mounted(){
      let par_id = this.$route.params.id
      if (JSON.parse(localStorage.getItem('realTimeForm'))) {
        this.form = JSON.parse(localStorage.getItem('realTimeForm'))
      }
      this.personHead = localStorage.getItem('personHead')
      this.personC = localStorage.getItem('personC')
      this.form.notifiers = JSON.parse(localStorage.getItem('notifiers'))
      this.form.handlers = JSON.parse(localStorage.getItem('handlers'))
      if (JSON.parse(localStorage.getItem('realTimeData'))) {
        let realTimeDatas = JSON.parse(localStorage.getItem('realTimeData'))
        this.quistionTypeVal = realTimeDatas.quistionTypeVal
        this.dangerLevelVal = realTimeDatas.dangerLevelVal
      }
      if (par_id) {
        realTimeInspectionAPI.getRealDetails(par_id).then(res => {
          this.form.pointDesc = res.pointDesc
          this.form.expireDate = res.expireDate
          this.form.category = res.trouble.category
          this.personHead = res.trouble.handlers.map(item => {
            return item.userName
          }).join(',')
          this.form.handlers = res.trouble.handlers.map(item => {
            return item.id
          })
          this.personC = res.trouble.notifiers.map(item => {
            return item.userName
          }).join(',')
          this.form.notifiers = res.trouble.notifiers.map(item => {
            return item.id
          })
          this.form.troubleDesc = res.trouble.troubleDesc
          this.quistionTypeVal = res.trouble.categoryName
          this.form.riskLevel = res.riskLevel
          if (res.riskLevel === 1) {
            this.dangerLevelVal = 'I级'
          } else if (res.riskLevel === 2) {
            this.dangerLevelVal = 'II级'
          } else {
            this.dangerLevelVal = 'III级'
          }
        })
      }
      this.getQuistionsList()
    }
  }
</script>

<style scoped lang="scss">
  .realTimeInspection{
    /deep/ .textarea .van-field__control{
      height: 7.5rem
    }
  }
</style>
